package com.naiterui.ehp.bp.utils.beans.ser;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.google.common.collect.Lists;
import com.naiterui.ehp.bp.utils.beans.annotation.Url;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.List;

public class UrlFieldDeserializer extends StdDeserializer<Object> implements ContextualDeserializer {

    private Url url;

    private JavaType javaType;

    private UrlFieldDeserializer(Url url, JavaType javaType) {
        this();
        this.url = url;
        this.javaType = javaType;
    }

    public UrlFieldDeserializer() {
        super(Object.class);
    }

    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        Object obj = jp.getCodec().readValue(jp, this.javaType);
        if (!this.url.deserialize()) {
            return obj;
        }
        if (obj instanceof String) {
            return this.getUrl((String) obj);
        } else if (obj instanceof List) {
            List<String> uriList = (List) obj;
            List<String> url = Lists.newArrayList();
            for (String o : uriList) {
                url.add(this.getUrl(o));
            }
            return url;
        }
        return obj;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        Url url = property.getAnnotation(Url.class);
        if (url != null) {
            return new UrlFieldDeserializer(url, property.getType());
        }
        return null;
    }

    private String getUrl(String uri) {
        if (StringUtils.isEmpty(uri)) {
            return uri;
        }
        if (!uri.startsWith("http")) {
            return uri;
        }
        String imgHost = ConfigUtil.getString(this.url.config());
        String host = StringUtils.isNotEmpty(this.url.host()) ? this.url.host() : imgHost;
        return uri.replaceAll(host, "");
    }

}
